/**
 * Copyright 2005 The Apache Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edi.client.plugin;

import java.io.File;
import java.io.FilenameFilter;
import java.net.URL;
import java.net.URLClassLoader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.edi.Kola;

public class PluginClassLoader extends URLClassLoader {
	private static final Log log = LogFactory.getLog(PluginClassLoader.class);
	 public PluginClassLoader() {
	        super(new URL[] {}, findParentClassLoader());
	    }
	 /**
	  * 加入class 文件夹，加入资源文件，jar包等
	  * @param folder
	  */
	 public void addFolder(File folder){
		 try{ 
			 File classesDir = new File(folder, "classes"); 
	         if (classesDir.exists()) { 
	             addURL(classesDir.toURL());
	         }
	         File libDir = new File(folder, "lib");
	            File[] jars = libDir.listFiles(new FilenameFilter() {
	                public boolean accept(File dir, String name) {
	                    return name.endsWith(".jar") || name.endsWith(".zip");
	                }
	            });
	            if (jars != null) {
	                for (int i = 0; i < jars.length; i++) {
	                    if (jars[i] != null && jars[i].isFile()) {
	                    	addURL(jars[i].toURL());
	                    }
	                }
	            }
		 }catch(Exception e){
			 e.printStackTrace();
			 log.error("addFolder error "+e);
		 }
		
	 }
	 private static ClassLoader findParentClassLoader() {
	        ClassLoader parent = Kola.class.getClassLoader();
	        if (parent == null) {
	            parent = PluginClassLoader.class.getClassLoader();
	        }
	        if (parent == null) {
	            parent = ClassLoader.getSystemClassLoader();
	        }
	        return parent;
	    }
}
